package com.google.code.retrobox.editor.sprites;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.Timer;

import javax.swing.JPanel;

public class JImagePanel extends JPanel implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2974863756487507501L;
	private BufferedImage[] images;

	private int x, y;

	private int currentImage = 0, animationDelay = 500;

	private Timer animationTimer;

	public JImagePanel(BufferedImage[] images, int x, int y) {
		super();
		this.images = images;
		this.x = x;
		this.y = y;
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.drawImage(images[currentImage], x, y, null);
		if(animationTimer != null && animationTimer.isRunning()){
			currentImage++;
			if (currentImage >= getImageCount()) {
				currentImage = 0;
			}
		}
	}
	

	public void actionPerformed(ActionEvent e) {
		repaint();
	}

	public void startAnimation() {
		if (animationTimer == null) {
			currentImage = 0;
			animationTimer = new Timer(animationDelay, this);
			animationTimer.start();
		} else if (!animationTimer.isRunning())
			animationTimer.restart();
	}

	public void stopAnimation() {
		if (animationTimer != null) {
			animationTimer.stop();
		}
	}

	public void setBufferedImage(BufferedImage bufferedImage) {
		BufferedImage[] buffer = new BufferedImage[1];
		this.stopAnimation();
		buffer[0] = bufferedImage;
		this.images = buffer;
		this.repaint();

	}

	public int getImageCount() {
		if (images != null) {
			return this.images.length;
		} else {
			return 0;
		}
	}

	public int getAnimationDelay() {
		return animationDelay;
	}

	public void setAnimationDelay(int animationDelay) {
		this.animationDelay = animationDelay;
	}
	
	public BufferedImage[] getImages() {
		return images;
	}

	public void setImages(BufferedImage[] images) {
		this.images = images;
		this.repaint();
	}

	public void nextSprite() {
		this.stopAnimation();
		currentImage++;
		if(currentImage >= getImageCount()){
			currentImage = getImageCount() - 1;
		}
		this.repaint();
	}
	
	public void prevSprite() {
		this.stopAnimation();
		if(currentImage > 0){
			currentImage--;
		}
		this.repaint();
	}
}
